package cn.wawi.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import cn.wawi.common.easyui.DataGrid;
import cn.wawi.controller.BaseController;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.entity.sys.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/sys_user")
public class UserController extends BaseController<User>{
	
	@InitBinder({"department"})
	public void initBinder1(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("department.");
	}
	
	/**
	 * 用户列表,以json格式异步交互
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public DataGrid list(HttpServletRequest request){
		return findAllByPage(request);
	}

	/**
	 * 用户退出
	 */
	@RequestMapping(value="/exit",method=RequestMethod.GET)
	public String exit(HttpSession httpSession){
		httpSession.removeAttribute("loginUser");
		httpSession.invalidate();
		return "login";
	}
	/**
	 * 用户登陆
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(HttpSession session,HttpServletRequest request,User user){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("parentId", null);
		User loginUser=(User) session.getAttribute("loginUser");
        if(!request.getParameter("captcha").equalsIgnoreCase((String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))){
        	request.setAttribute("msg", "验证码错误!");
        	return "login";
        }else{
        	if(loginUser!=null){
        		map.put("userId",loginUser.getId());
        		List<Privilege> list=privilegeDao.findModel(map);
        		request.setAttribute("list", list);
        		return "index";
        	}else{
        		user=userDao.view(user);
        		if (user != null) {
        			session.setAttribute("loginUser", user);
            		map.put("userId",user.getId());
            		List<Privilege> list=privilegeDao.findModel(map);
        			request.setAttribute("list", list);
        			return "index";
        		} else {
        			request.setAttribute("msg", "用户名或密码不对!");
        			return "login";
        		}
        	}
        }
	}
}
